package com.suke.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.suke.bean.Article;
import com.suke.bean.User;
import com.suke.service.VoteSysService;
import com.suke.util.RedisUtil;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class VoteSysServiceImpl implements VoteSysService {

    Jedis jedis = RedisUtil.getJedis();

    //发布文章
    @Override
    public void punish(Article article, User user) {
        String index = jedis.incr("aIndex") + "";
        article.setAid(index);
        article.setUid(user.getUid());
        article.setPubTime(System.currentTimeMillis() + "");
        article.setVotes("0");
        String key = "article:" + index;
        RedisUtil.dbToRedis(article, jedis, 7, key);

        //用户发布文章的时候默认给自己投一个票
        jedis.hincrBy(key, "votes", 1);

        //按发布时间
        jedis.zadd("time:info", Double.parseDouble(article.getPubTime()), key);

        //按投票数排序
        jedis.zadd("votes:info", Double.parseDouble(jedis.hget(key, "votes")), key);

        //记录这篇文章被谁投过票了
        jedis.sadd("voted:" + index, user.getUid());
    }

    @Override
    public boolean vote(String aid, String uid) {
        jedis.select(7);
        //超过七天不能投票
        //获取当前时间
        long now = System.currentTimeMillis();

        //根据主键查询文章
        Article article = queryByAid(aid);
        //获取发布时间
        long pubTime = Long.parseLong(article.getPubTime());
        if ((now - pubTime) > 7 * 24 * 3600 * 1000) {
            return false;
        }

        //投过票的不能重复投票 ,没值返回1，有值返回0
        /*
         * 1、能够把没投票的用户加入
         * 2、判断有没有重复投票
         * */
        if (jedis.sadd("voted:" + aid, uid) == 0) {
            return false;
        }

        String key = "article:" + aid;
        //开始投票
        //给文章的votes票数+1
        jedis.hincrBy(key, "votes", 1);

        //把文章最新的票数加入到按投票数排序那个zset中
        jedis.zadd("votes:info", Double.parseDouble(jedis.hget(key, "votes")), key);

        return true;
    }

    @Override
    public List<Article> orderByVotes(String ascOrDesc) {
        jedis.select(7);
        List<Article> articles = new ArrayList<>();
        Set<String> members = null;
        if ("asc".equals(ascOrDesc)) {
            //查询按时间排序的所有文章(member)
            members = jedis.zrange("votes:info", 0, -1);
        } else {
            members = jedis.zrevrange("votes:info", 0, -1);
        }
        for (String member : members) {
            Map<String, String> map = jedis.hgetAll(member);
            Article article = BeanUtil.mapToBean(map, Article.class, false,
                    new CopyOptions().ignoreNullValue());

            //取出发布时间，格式化
            String pubTime = article.getPubTime();
            Date date = new Date(Long.parseLong(pubTime));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            article.setPubTime(simpleDateFormat.format(date));
            //发布者，根据外键查询用户
            //取出用户主键
            String uid = article.getUid();

            Map<String, String> userMap = jedis.hgetAll("user:" + uid);
            User user = BeanUtil.mapToBean(userMap, User.class, false,
                    new CopyOptions().ignoreNullValue());
            article.setUid(user.getUsername());

            articles.add(article);
        }
        return articles;
    }

    @Override
    public List<Article> orderByTime(String ascOrDesc) {
        jedis.select(7);
        List<Article> articles = new ArrayList<>();
        Set<String> members = null;
        if ("asc".equals(ascOrDesc)) {
            //查询按时间排序的所有文章(member)
            members = jedis.zrange("time:info", 0, -1);
        } else {
            members = jedis.zrevrange("time:info", 0, -1);
        }
        for (String member : members) {
            Map<String, String> map = jedis.hgetAll(member);
            Article article = BeanUtil.mapToBean(map, Article.class, false,
                    new CopyOptions().ignoreNullValue());

            //取出发布时间，格式化
            String pubTime = article.getPubTime();
            Date date = new Date(Long.parseLong(pubTime));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            article.setPubTime(simpleDateFormat.format(date));
            //发布者，根据外键查询用户
            //取出用户主键
            String uid = article.getUid();

            Map<String, String> userMap = jedis.hgetAll("user:" + uid);
            User user = BeanUtil.mapToBean(userMap, User.class, false,
                    new CopyOptions().ignoreNullValue());
            article.setUid(user.getUsername());

            articles.add(article);
        }
        return articles;
    }

    @Override
    public Article queryByAid(String aid) {
        jedis.select(7);
        String key = "article:" + aid;
        Map<String, String> map = jedis.hgetAll(key);
        Article article = BeanUtil.mapToBean(map, Article.class, false,
                new CopyOptions().ignoreNullValue());
        return article;
    }

    @Override
    public User login(User user) {
        jedis.select(7);
        //取出所有用户
        Set<String> keys = jedis.keys("user:*");
        for (String key : keys) {
            Map<String, String> map = jedis.hgetAll(key);
            String username = map.get("username");
            String password = map.get("password");

            if (username.equals(user.getUsername()) && password.equals(user.getPassword())) {
                //Map转Bean
                user = BeanUtil.mapToBean(map, User.class, false,
                        new CopyOptions().ignoreNullValue());
            }

        }
        return user;
    }
}
